package cn.wuxing.mediation.web.controller.common;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.wuxing.mediation.businessplatform.domain.pojo.AreaVO;
import cn.wuxing.mediation.businessplatform.mapper.business.CmNotDisputeEventMapper;
import cn.wuxing.mediation.businessplatform.mapper.system.AreaMapper;
import cn.wuxing.mediation.common.core.domain.entity.CmNotDisputeEvent;
import cn.wuxing.mediation.infoconfig.domain.vo.IcWindowListVO;
import cn.wuxing.mediation.infoconfig.mapper.IcWindowMapper;
import cn.wuxing.mediation.web.imports.domain.ImportNonDisputeEvent;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NonDisputeEventListener implements ReadListener<ImportNonDisputeEvent> {
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    private static final Logger log = LoggerFactory.getLogger(NonDisputeEventListener.class);
    private final CmNotDisputeEventMapper notDisputeEventMapper;
    private final AreaMapper areaMapper;
    private final IcWindowMapper windowMapper;
    /**
     * 缓存的数据
     */
    private List<ImportNonDisputeEvent> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    // 定义映射关系
    private static final Map<String, Integer> STATUS_MAP = new HashMap<>();

    /**
     * 在转换异常 获取其他异常下会调用本接口。抛出异常则停止读取。如果这里不抛出异常则 继续读取下一行。
     *
     * @param exception
     * @param context
     * @throws Exception
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) {
        log.error("解析失败，但是继续解析下一行:", exception);
        // 如果是某一个单元格的转换异常 能获取到具体行号
        // 如果要获取头的信息 配合invokeHeadMap使用
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            log.error("第{}行，第{}列解析异常，数据为:{}", excelDataConvertException.getRowIndex(),
                    excelDataConvertException.getColumnIndex(), JSONUtil.toJsonStr(excelDataConvertException.getCellData()));
        }
    }

    static {
        //案件状态 1.待分派 2.受理退回 3.待受理 4.待调解 5.待二次分派 6.待二次受理 7.待二次调解 8.待结案 9.待二次结案 10.已结案
        STATUS_MAP.put("待分派", 1);
        STATUS_MAP.put("受理退回", 2);
        STATUS_MAP.put("待受理", 3);
        STATUS_MAP.put("待调解", 4);
        STATUS_MAP.put("待二次分派", 5);
        STATUS_MAP.put("待二次受理", 6);
        STATUS_MAP.put("待二次调解", 7);
        STATUS_MAP.put("待结案", 8);
        STATUS_MAP.put("待二次结案", 9);
        STATUS_MAP.put("已结案", 10);
    }

    /**
     * 将案件状态从字符串转换为整数
     *
     * @param status 案件状态字符串
     * @return 对应的整数值；如果找不到对应关系，返回 -1
     */
    public static int convertStatus(String status) {
        return STATUS_MAP.getOrDefault(status, -1);
    }

    public NonDisputeEventListener(CmNotDisputeEventMapper notDisputeEventMapper, AreaMapper areaMapper, IcWindowMapper windowMapper) {
        this.notDisputeEventMapper = notDisputeEventMapper;
        this.areaMapper = areaMapper;
        this.windowMapper = windowMapper;
    }

    @Override
    public void invoke(ImportNonDisputeEvent event, AnalysisContext analysisContext) {
        log.info("【非纠纷事件导入解析】-解析到一条数据：{}", JSONUtil.toJsonStr(event));
        cachedDataList.add(event);

        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("【非纠纷事件导入解析】- 所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("【非纠纷事件导入解析】- {}条数据，开始存储数据库！", cachedDataList.size());
        if (cachedDataList.isEmpty()) {
            log.warn("【非纠纷事件导入解析】- 解析的数据为空，忽略存储数据库操作。");
            return;
        }
        //遍历组装数据
        cachedDataList.forEach(eventExcel -> {
            try {
                CmNotDisputeEvent eventEntity = new CmNotDisputeEvent();
                eventEntity.setId(eventExcel.getIdx());
                eventEntity.setEventCode(eventExcel.getEventCode());
                eventEntity.setEventState(convertStatus(eventExcel.getEventState()));
                //事项类型 1.法律援助咨询 2.劳动纠纷咨询 3.已专窗名称进行分类

                String eventType = "3";
//            switch (eventExcel.getEventType()) {
//                case "法律援助咨询":
//                    eventType = "1";
//                    break;
//                case "劳动纠纷咨询":
//                    eventType = "2";
//                    break;
//                default:
//                    eventType = "3";
//                    break;
//            }
                eventEntity.setEventType(eventType);
                //如果是yyyy-MM-dd，则parseDate，否则parseTime
                if (eventExcel.getInitiateTime().length() <= 10) {
                    eventEntity.setInitiateTime(DateUtil.parseDate(eventExcel.getInitiateTime()));
                } else {
                    eventEntity.setInitiateTime(DateUtil.parseDateTime(eventExcel.getInitiateTime()));
                }
                eventEntity.setPeopleNum(StrUtil.isNotBlank(eventExcel.getVisitorNum()) ? Integer.valueOf(eventExcel.getVisitorNum()) : null);
                String[] areaArrays = eventExcel.getArea().split("/");
                String lastArea = areaArrays[areaArrays.length - 1];

                eventEntity.setAreaId(getAreaName(lastArea, null));
                eventEntity.setEventDesc(eventExcel.getEventDesc());
                List<IcWindowListVO> icWindowListVOS = windowMapper.selectLikeWindowName(eventExcel.getEventType());
                if (icWindowListVOS != null && !icWindowListVOS.isEmpty()) {
                    eventEntity.setWindowId(icWindowListVOS.get(0).getId());
                    eventEntity.setEventType(String.valueOf(icWindowListVOS.get(0).getId()));
                }
//            eventEntity.setCloseCaseContent(eventExcel.getCloseEventDesc());
                notDisputeEventMapper.insert(eventEntity);
            } catch (Exception ex) {
                log.error("【非纠纷事件导入解析】- 存储数据库失败。", ex);
            }
        });
        log.info("【非纠纷事件导入解析】- 存储数据库成功！");
    }

    private  String getAreaName(String parentName, String parentAreaId) {
        if (parentName.equals("吴兴区")){
            parentName = "高新区";
        }
        AreaVO areaByName = areaMapper.getAreaByName(parentName);
        if (areaByName != null) {
            if (areaByName.getLevel() == 3) {
                return areaByName.getAreaId();
            } else if (areaByName.getLevel() == 2 || areaByName.getLevel() == 1){
                AreaVO NextId = areaMapper.getAreaNextId(Long.parseLong(areaByName.getAreaId()));
                return getAreaName(NextId.getAreaName(), NextId.getAreaId());
            } else  {
                return getAreaName(areaByName.getAreaName(), areaByName.getAreaId());
            }
        }
        return parentAreaId;
    }

}
